package de.westranger.forex.trading.genetic.allel.fitness;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import de.westranger.forex.trading.GlobalConfig;
import de.westranger.forex.trading.genetic.ContentResolver;
import de.westranger.forex.trading.genetic.allel.chromosom.CompositeChromosom;

public final class ParallelComputeCompositeFitness {

	private final int numTasks;
	private final int numThreads;
	
	public ParallelComputeCompositeFitness(final int numThreads){
		this.numTasks = numThreads*GlobalConfig.TASKS_PER_THREAD;
		this.numThreads = numThreads;
	}
	
	public void produce(final CompositeChromosom[] population, final ContentResolver conRes){
			final int mod = population.length%numTasks;
			final int fac = (population.length-mod)/numTasks;
			final ExecutorService es = Executors.newFixedThreadPool(numThreads);

			for(int i=0;i<numTasks-1;i++){
				es.submit(new ComputeCompositeFitnesWorker(population,conRes.clone(),i*fac,(i+1)*fac));
			}
			es.submit(new ComputeCompositeFitnesWorker(population,conRes.clone(),(numTasks-1)*fac,(numTasks*fac)+mod));
	        es.shutdown();
	        
	        try {
				es.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	}
	
}
